package com.hue.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hue.entity.EduSubject;
import com.hue.entity.excel.SubjectData;
import com.hue.service.EduSubjectService;

public class ReadExcelListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService eduSubjectService;

    public ReadExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData!=null){
            if(oneSubject(subjectData.getOneSubjectName())==null){  //该一级分类不存在
                //添加该一级分类
                EduSubject eduSubject = new EduSubject();
                eduSubject.setTitle(subjectData.getOneSubjectName());
                eduSubject.setParentId("0");
                eduSubjectService.save(eduSubject);
            }

            //查询一级分类的ID
            String parentId = oneSubject(subjectData.getOneSubjectName()).getId();

            if(twoSubject(subjectData.getTwoSubjectName(),parentId)==null){  //该二级分类不存在
                //添加该一级分类
                EduSubject eduSubject = new EduSubject();
                eduSubject.setTitle(subjectData.getTwoSubjectName());
                eduSubject.setParentId(parentId);
                eduSubjectService.save(eduSubject);
            }
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    //判断以一级分类是否存在
    private EduSubject oneSubject(String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id", "0");
        EduSubject eduSubject = eduSubjectService.getOne(wrapper);
        return eduSubject;
    }

    //判断以二级分类是否存在
    private EduSubject twoSubject(String name,String parentId){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id", parentId);
        EduSubject twoSubject = eduSubjectService.getOne(wrapper);
        return twoSubject;
    }
}
